<?php
namespace App\Common\Ai;
use App\Common\Logs\Logs;
use App\Common\Utill\Utills;
use Illuminate\Support\Facades\Log;

/**
 * 星火认知大模型-Spark Max
 * http调用文档: https://www.xfyun.cn/doc/spark/HTTP%E8%B0%83%E7%94%A8%E6%96%87%E6%A1%A3.html
 */
class XFYunApi
{
    //请求地址
    protected static $url = "https://spark-api-open.xf-yun.com/v1/chat/completions";
    //密码
    protected static $apiPassword = "YOkLeLETWpCwaKnmZmYP:DJfQRiVEFggwAaRhxtKl";

    /**
     * ai生成文章标题或者内容
     * @param $instruction //信息
     * @param $type //1=ai生成文章标题 2=ai生成文章内容
     * @return void
     */
    public function sendRequest($aiOrderSn, $instruction, $type = 1)
    {
        $describe = "ai生成文章标题";
        if ($type == 2) {
            $describe = "ai生成文章内容";
        }
        try {
            $params["model"] = "generalv3.5";
//            $params["model"] = "4.0Ultra";
            $params["messages"] = array(
                array(
                    "role" => "user",
                    "content" => $instruction
                )
            );
            $url = self::$url;
            $apiPassword = self::$apiPassword;
            $beginTime = time();
            Logs::info("订单id:{$aiOrderSn},开始运行:" . $describe . ",url:{$url}", $params,1,'xfYun');
            $data = Utills::postCurl($url, $params, $apiPassword);
            if ($data['message'] != "Success") {
                throw new \Exception("服务返回报错" . json_encode($data, JSON_UNESCAPED_UNICODE));
            }
            $returnData['code'] = $data['code'];
            $returnData['message'] = $data['message'];
            $returnData['totalTokens'] = $data["usage"]["total_tokens"];
            $content = $data['choices'][0]['message']['content'];
            $returnData['content'] = $content;
            $returnData['return_content'] = $data;
            $endtime = time();
            $userTime = $endtime - $beginTime;
            Logs::info("订单id：{$aiOrderSn},耗时:{$userTime}秒,返回结果:" . $describe, $data,1,'xfYun');
            return $returnData;

        } catch (\Exception $e) {
            $log = [
                "postion" => $describe,
                "params" => json_encode($params, JSON_UNESCAPED_UNICODE),
                "message" => $e->getMessage(),
                "file" => $e->getFile(),
                "line" => $e->getLine(),
                "code" => $e->getCode()
            ];
            Logs::error("ai生成文章标题或者内容-fail", $log);
        }

    }



}
